import axios from 'axios';

// OpenWeatherMap API配置
const API_KEY = '5c633370cd91b876c609487ececfb510'; // 需要替换为实际的API密钥
const BASE_URL = 'https://api.openweathermap.org/data/2.5';
const GEO_URL = 'https://api.openweathermap.org/geo/1.0';

// 创建axios实例
const weatherApi = axios.create({
  baseURL: BASE_URL,
  params: {
    appid: API_KEY,
    lang: 'zh_cn', // 返回中文数据
    units: 'metric' // 使用摄氏度
  }
});

const geoApi = axios.create({
  baseURL: GEO_URL,
  params: {
    appid: API_KEY,
    limit: 5 // 默认返回5个结果
  }
});

// 将OpenWeatherMap的数据格式转换为我们应用中使用的格式
const formatCurrentWeather = (data) => {
  if (!data) return null;
  
  return {
    temp: Math.round(data.main.temp),
    feelsLike: Math.round(data.main.feels_like),
    humidity: data.main.humidity,
    pressure: data.main.pressure,
    windSpeed: data.wind.speed,
    windDir: getWindDirection(data.wind.deg),
    windScale: getWindScale(data.wind.speed),
    text: data.weather[0].description,
    icon: data.weather[0].id.toString(),
    obsTime: new Date().toISOString(),
    vis: data.visibility / 1000 // 转换为公里
  };
};

const formatForecast = (data) => {
  if (!data || !data.daily) return [];
  
  return data.daily.slice(0, 3).map(day => {
    return {
      fxDate: new Date(day.dt * 1000).toISOString().split('T')[0],
      tempMax: Math.round(day.temp.max),
      tempMin: Math.round(day.temp.min),
      iconDay: day.weather[0].id.toString(),
      textDay: day.weather[0].description,
      windDirDay: getWindDirection(day.wind_deg),
      windScaleDay: getWindScale(day.wind_speed),
      sunrise: new Date(day.sunrise * 1000).toISOString().split('T')[1].substring(0, 5),
      sunset: new Date(day.sunset * 1000).toISOString().split('T')[1].substring(0, 5),
      humidity: day.humidity,
      precip: day.rain ? day.rain : 0,
      pressure: day.pressure
    };
  });
};

// 生成生活指数数据
const generateLifeIndices = (current, forecast) => {
  if (!current || !forecast || forecast.length === 0) return [];
  
  const indices = [];
  
  // 运动指数
  indices.push({
    type: '1',
    name: '运动指数',
    level: getActivityLevel(current.main.temp, current.wind.speed, current.weather[0].id),
    category: getActivityCategory(current.main.temp, current.wind.speed, current.weather[0].id),
    text: getActivityText(current.main.temp, current.wind.speed, current.weather[0].id)
  });
  
  // 洗车指数
  indices.push({
    type: '2',
    name: '洗车指数',
    level: getCarWashLevel(current.weather[0].id, forecast[0].pop),
    category: getCarWashCategory(current.weather[0].id, forecast[0].pop),
    text: getCarWashText(current.weather[0].id, forecast[0].pop)
  });
  
  // 穿衣指数
  indices.push({
    type: '3',
    name: '穿衣指数',
    level: getDressingLevel(current.main.temp),
    category: getDressingCategory(current.main.temp),
    text: getDressingText(current.main.temp)
  });
  
  // 紫外线指数
  indices.push({
    type: '5',
    name: '紫外线指数',
    level: getUVLevel(current.uvi || forecast[0].uvi),
    category: getUVCategory(current.uvi || forecast[0].uvi),
    text: getUVText(current.uvi || forecast[0].uvi)
  });
  
  return indices;
};

// 获取风向文字
const getWindDirection = (degree) => {
  const directions = [
    '北风', '东北风', '东风', '东南风',
    '南风', '西南风', '西风', '西北风'
  ];
  
  const index = Math.round(degree / 45) % 8;
  return directions[index];
};

// 获取风力等级
const getWindScale = (speed) => {
  if (speed < 0.3) return '0';
  if (speed < 1.6) return '1';
  if (speed < 3.4) return '2';
  if (speed < 5.5) return '3';
  if (speed < 8.0) return '4';
  if (speed < 10.8) return '5';
  if (speed < 13.9) return '6';
  return '7';
};

// 运动指数相关函数
const getActivityLevel = (temp, windSpeed, weatherCode) => {
  // 根据温度、风速和天气状况计算运动适宜度
  if (weatherCode >= 200 && weatherCode < 600) return '5'; // 雨雪天气
  if (temp < 5 || temp > 35) return '4'; // 温度过低或过高
  if (windSpeed > 10) return '3'; // 风速较大
  return '1'; // 适宜运动
};

const getActivityCategory = (temp, windSpeed, weatherCode) => {
  const level = getActivityLevel(temp, windSpeed, weatherCode);
  switch (level) {
    case '1': return '适宜';
    case '2': return '较适宜';
    case '3': return '一般';
    case '4': return '较不宜';
    case '5': return '不宜';
    default: return '一般';
  }
};

const getActivityText = (temp, windSpeed, weatherCode) => {
  const level = getActivityLevel(temp, windSpeed, weatherCode);
  switch (level) {
    case '1': return '天气适宜运动，可以尽情进行户外活动。';
    case '2': return '天气较适宜运动，适当注意天气变化。';
    case '3': return '天气一般，户外运动请注意防护。';
    case '4': return '天气较不宜运动，建议室内活动为主。';
    case '5': return '天气不宜运动，建议避免户外活动。';
    default: return '天气一般，户外运动请注意防护。';
  }
};

// 洗车指数相关函数
const getCarWashLevel = (weatherCode, rainProb) => {
  if (weatherCode >= 200 && weatherCode < 600) return '5'; // 雨雪天气
  if (rainProb > 0.5) return '4'; // 降水概率高
  if (weatherCode >= 600 && weatherCode < 700) return '3'; // 雾霾等
  return '1';
};

const getCarWashCategory = (weatherCode, rainProb) => {
  const level = getCarWashLevel(weatherCode, rainProb);
  switch (level) {
    case '1': return '适宜';
    case '2': return '较适宜';
    case '3': return '一般';
    case '4': return '较不宜';
    case '5': return '不宜';
    default: return '一般';
  }
};

const getCarWashText = (weatherCode, rainProb) => {
  const level = getCarWashLevel(weatherCode, rainProb);
  switch (level) {
    case '1': return '天气较好，适合洗车，洗车后不会很快变脏。';
    case '2': return '较适宜洗车，未来一天内无雨。';
    case '3': return '一般适宜洗车，建议选择专业洗车服务。';
    case '4': return '较不宜洗车，可能会有降水。';
    case '5': return '不宜洗车，有雨雪天气，洗车后很快会变脏。';
    default: return '一般适宜洗车，请根据实际天气情况决定。';
  }
};

// 穿衣指数相关函数
const getDressingLevel = (temp) => {
  if (temp < 0) return '5';
  if (temp < 10) return '4';
  if (temp < 15) return '3';
  if (temp < 25) return '2';
  return '1';
};

const getDressingCategory = (temp) => {
  const level = getDressingLevel(temp);
  switch (level) {
    case '1': return '炎热';
    case '2': return '舒适';
    case '3': return '较凉';
    case '4': return '寒冷';
    case '5': return '极冷';
    default: return '舒适';
  }
};

const getDressingText = (temp) => {
  const level = getDressingLevel(temp);
  switch (level) {
    case '1': return '天气炎热，建议穿轻薄透气的衣物，注意防晒。';
    case '2': return '天气舒适，建议穿长袖衬衫或薄外套。';
    case '3': return '天气较凉，建议穿长袖衬衫、单裤等服装。';
    case '4': return '天气寒冷，建议穿棉衣、羊毛衫等保暖衣物。';
    case '5': return '天气极冷，建议穿厚羽绒服、冬大衣等厚重保暖衣物。';
    default: return '天气舒适，建议穿长袖衬衫或薄外套。';
  }
};

// 紫外线指数相关函数
const getUVLevel = (uvi) => {
  if (uvi < 3) return '1';
  if (uvi < 6) return '2';
  if (uvi < 8) return '3';
  if (uvi < 11) return '4';
  return '5';
};

const getUVCategory = (uvi) => {
  const level = getUVLevel(uvi);
  switch (level) {
    case '1': return '最弱';
    case '2': return '弱';
    case '3': return '中等';
    case '4': return '强';
    case '5': return '极强';
    default: return '中等';
  }
};

const getUVText = (uvi) => {
  const level = getUVLevel(uvi);
  switch (level) {
    case '1': return '紫外线强度最弱，无需采取防护措施。';
    case '2': return '紫外线强度较弱，建议涂擦SPF在12-15之间的防晒霜。';
    case '3': return '紫外线强度中等，建议涂擦SPF在15-30之间的防晒霜。';
    case '4': return '紫外线强度较强，建议涂擦SPF在30-50之间的防晒霜。';
    case '5': return '紫外线强度极强，建议尽量避免外出，必须外出时涂擦SPF大于50的防晒霜。';
    default: return '紫外线强度中等，建议涂擦SPF在15-30之间的防晒霜。';
  }
};

// 获取实时天气数据
export const getNowWeather = async (location) => {
  try {
    let lat, lon;
    
    // 如果location是经纬度格式
    if (typeof location === 'string' && location.includes(',')) {
      [lon, lat] = location.split(',');
    } 
    // 如果location是城市ID
    else if (typeof location === 'string') {
      lat = location.lat;
      lon = location.lon;
    }
    
    const response = await weatherApi.get('/weather', {
      params: { lat, lon }
    });
    
    return {
      code: '200',
      now: formatCurrentWeather(response.data)
    };
  } catch (error) {
    console.error('获取实时天气失败:', error);
    throw error;
  }
};

// 获取未来天气预报
export const get3DayForecast = async (location) => {
  try {
    let lat, lon;
    
    // 如果location是经纬度格式
    if (typeof location === 'string' && location.includes(',')) {
      [lon, lat] = location.split(',');
    } 
    // 如果location是城市ID
    else if (typeof location === 'object') {
      lat = location.lat;
      lon = location.lon;
    }
    
    const response = await weatherApi.get('/onecall', {
      params: { 
        lat, 
        lon,
        exclude: 'minutely,hourly,alerts' // 排除不需要的数据
      }
    });
    
    return {
      code: '200',
      daily: formatForecast(response.data)
    };
  } catch (error) {
    console.error('获取天气预报失败:', error);
    throw error;
  }
};

// 获取生活指数
export const getLifeIndices = async (location) => {
  try {
    let lat, lon;
    
    // 如果location是经纬度格式
    if (typeof location === 'string' && location.includes(',')) {
      [lon, lat] = location.split(',');
    } 
    // 如果location是城市ID
    else if (typeof location === 'object') {
      lat = location.lat;
      lon = location.lon;
    }
    
    // 获取当前天气和预报数据，用于生成生活指数
    const [currentResponse, forecastResponse] = await Promise.all([
      weatherApi.get('/weather', { params: { lat, lon } }),
      weatherApi.get('/onecall', { 
        params: { 
          lat, 
          lon,
          exclude: 'minutely,hourly,alerts'
        }
      })
    ]);
    
    const indices = generateLifeIndices(currentResponse.data, forecastResponse.data.daily);
    
    return {
      code: '200',
      daily: indices
    };
  } catch (error) {
    console.error('获取生活指数失败:', error);
    throw error;
  }
};

// 城市搜索
export const searchCity = async (keyword) => {
  try {
    const response = await geoApi.get('/direct', {
      params: { q: keyword }
    });
    
    // 转换为和风天气API格式
    const locations = response.data.map(city => ({
      id: `${city.lat},${city.lon}`,
      name: city.local_names?.zh || city.name,
      lat: city.lat,
      lon: city.lon,
      adm1: city.state || '',
      adm2: '',
      country: city.country
    }));
    
    return {
      code: '200',
      location: locations
    };
  } catch (error) {
    console.error('城市搜索失败:', error);
    throw error;
  }
};

export default {
  getNowWeather,
  get3DayForecast,
  getLifeIndices,
  searchCity
};
